﻿@{
    Layout = "~/Views/Shared/_SysPage.cshtml";
}
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
@section header{
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/zTree/v3/css/metroStyle/metroStyle.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/zTree/v3/js/ztree.min.js"))

    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/jquery.layout/1.4.4/jquery.layout-latest.min.css"))
    @BundlerHelper.Render(HostingEnvironment.ContentRootPath, Url.Content("~/lib/jquery.layout/1.4.4/jquery.layout-latest.min.js"))
}

<div class="ui-layout-west">
    <div class="main-content">
        <div class="box box-main">
            <div class="box-header">
                <div class="box-title">
                    组织机构
                </div>

                <div class="box-tools pull-right">
                    <a type="button" class="btn btn-box-tool menuItem" href="#" onclick="showManageOrganization()" title="管理组织"><i class="fa fa-edit"></i></a>
                    <button type="button" class="btn btn-box-tool" id="btnExpandTree" title="展开" style="display:none;"><i class="fa fa-chevron-up"></i></button>
                    <button type="button" class="btn btn-box-tool" id="btnCollapseTree" title="折叠"><i class="fa fa-chevron-down"></i></button>
                    <button type="button" class="btn btn-box-tool" id="btnRefreshMaster" title="刷新组织"><i class="fa fa-refresh"></i></button>

                </div>
            </div>
            <div class="ui-layout-content">
                <div id="masterTree" class="ztree"></div>
            </div>
        </div>
    </div>
</div>

<div class="container-div ui-layout-center">
    <div class="row">
        <div id="searchDiv" class="col-sm-12 search-collapse">
            <input type="hidden" id="masterId" col="MasterId">
            <div class="select-list">
                <ul>
                    <li>
                        <label style="margin-top:4px">多层搜索：</label>
                    </li>
                    <li style="width:60px">
                        <span id="recursiveSearch" col="RecursiveSearch"></span>
                    </li>
                    <li>
                        状态：<span id="status" col="Status"></span>
                    </li>
                    <li>
                        姓名或描述：<input id="text" col="Text" type="text" />
                    </li>
                    <li>
                        账号/手机/邮件/微信：<input id="mark" col="Mark" type="text" />
                    </li>

                    <li class="select-time">
                        <label>创建时间： </label>
                        <input id="startCreationTime" col="StartCreationTime" type="text" class="time-input" placeholder="开始时间" />
                        <span>-</span>
                        <input id="endCreationTime" col="EndCreationTime" type="text" class="time-input" placeholder="结束时间" />
                    </li>
                    <li>
                        <a id="btnSearch" class="btn btn-primary btn-sm" onclick="searchGrid()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                    </li>
                </ul>
            </div>
        </div>

        <div id="toolbar" class="btn-group-sm">
            <a id="btnAdd" class="btn btn-success" onclick="showAddEditDialog(true)"><i class="fa fa-plus"></i> 新增</a>
            <a id="btnEdit" class="btn btn-primary disabled" onclick="showAddEditDialog(false)"><i class="fa fa-edit"></i> 修改</a>
            <a id="btnManageRoles" class="btn btn-primary disabled" onclick="showUpdateBelongedUserGroupsDialog(@((int)UserGroupType.Role))"><i class="fa fa-edit"></i> 管理角色</a>
            <a id="btnManageAuthGroups" class="btn btn-primary disabled" onclick="showUpdateBelongedUserGroupsDialog(@((int)UserGroupType.AuthorizationGroup))"><i class="fa fa-edit"></i> 管理权限组</a>
            <a id="btnManageCommGroups" class="btn btn-primary disabled" onclick="showUpdateBelongedUserGroupsDialog(@((int)UserGroupType.CommunicationGroup))"><i class="fa fa-edit"></i> 管理通讯组</a>
            <a id="btnUploadThumbnail" class="btn btn-info disabled" onclick="showUploadThumbnailDialog()"><i class="fa fa-upload"></i> 上传缩略图</a>
            <a id="btnDelete" class="btn btn-danger disabled" onclick="deleteSelected()"><i class="fa fa-remove"></i> 删除</a>
        </div>

        <div class="col-sm-12 select-table table-striped">
            <table id="gridTable" data-mobile-responsive="true"></table>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        $("#status").ysComboBox({data: ys.getJson(@Html.Raw(typeof(StatusType).EnumToDictionaryJson())) });
        $("#recursiveSearch").ysComboBox({class: 'no-additional-option', data: ys.getJson(@Html.Raw(typeof(YesOrNo).EnumToDictionaryJson()))});
        initTree();
        initGrid();
        $("#gridTable").on("check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table", function () {
            var selectedRows = $("#gridTable").bootstrapTable("getSelections");
            if ($('#btnManageRoles')) {
                $('#btnManageRoles').toggleClass('disabled', selectedRows.length != 1);
            }
            if ($('#btnManageAuthGroups')) {
                $('#btnManageAuthGroups').toggleClass('disabled', selectedRows.length != 1);
            }
            if ($('#btnManageCommGroups')) {
                $('#btnManageCommGroups').toggleClass('disabled', selectedRows.length != 1);
            }
            if ($('#btnUploadThumbnail')) {
                $('#btnUploadThumbnail').toggleClass('disabled', selectedRows.length != 1);
            }
        });

        $('body').layout({ west__size: 185 });
        laydate.render({ elem: '#startCreationTime', format: 'yyyy-MM-dd' });
        laydate.render({ elem: '#endCreationTime', format: 'yyyy-MM-dd' });

        $('#btnExpandTree').click(function () {
            var tree = $.fn.zTree.getZTreeObj("masterTree");
            tree.expandAll(true);
            $(this).hide();
            $('#btnCollapseTree').show();
        });

        $('#btnCollapseTree').click(function () {
            var tree = $.fn.zTree.getZTreeObj("masterTree");
            tree.expandAll(false);
            $(this).hide();
            $('#btnExpandTree').show();
        });

        $('#btnRefreshMaster').click(function () {
            initTree();
        });

    });

    function initTree() {
        $('#masterTree').ysTree({
            url: '@Url.Content("~/Sys/User/GetOrganizationTreeJsonForManage")',
            async: true,
            expandLevel: 2,
            maxHeight: "800px",
            callback: {
                onClick: function (event, treeId, treeNode) {
                    $("#masterId").val(treeNode.id);
                    searchGrid();
                }
            }
        });
    }

    function initGrid() {
        var queryUrl = '@Url.Content("~/sys/User/GetPagedManageDtosJson")';
        $('#gridTable').ysTable({
            url: queryUrl,
            sortName: 'Account',
            sortOrder: 'Asc',
            toolbar: '#toolbar',
            columns: [
                { checkbox: true, visible: true },

                { field: 'Account', title: '账号', sortable: true },
                { field: 'Name', title: '姓名' , sortable: true },
                { field: 'MasterCascadePath', title: '组织' },
                { field: 'Mobile', title: '手机', width: '100px'},
                {
                    field: 'HasThumbnail', title: '缩略图', width: '60px',
                    formatter: function (value, row, index) {
                        if (row.HasThumbnail == "@((int)HasOrNone.Has)") {
                            return '<span class="badge badge-primary">' + "@HasOrNone.Has.GetDescription()" + '</span>';
                        } else {
                            return '<span class="badge badge-warning">' + "@HasOrNone.None.GetDescription()" + '</span>';
                        }
                    }
                },
                {
                    field: 'Status', title: '状态', width: '40px', sortable: true,
                    formatter: function (value, row, index) {
                        if (row.Status == "@((int)StatusType.Enabled)") {
                            return '<span class="badge badge-primary">' + "@StatusType.Enabled.GetDescription()" + '</span>';
                        } else {
                            return '<span class="badge badge-warning">' + "@StatusType.Disabled.GetDescription()" + '</span>';
                        }
                    }
                },
                {
                    field: 'ModificationTime', title: '修改时间', width:'150px',sortable: true,
                    formatter: function (value, row, index) {
                        return ys.formatDate(value, "yyyy-MM-dd HH:mm:ss");
                    }
                },
                { field: 'Id', title: 'Id', width: '100px',visible: false },
                {
                    title: '操作',
                    align: 'center', width: '100px',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-warning btn-xs" href="#" onclick="showResetPasswordDialog(\'' + row.Id + '\')"><i class="fa fa-key"></i>重置密码</a>');
                        return actions.join('');
                    }
                }
            ],
            queryParams: function (params) {
                var pagination = $('#gridTable').ysTable('getPagination', params);
                queryString = $("#searchDiv").getWebControls(pagination);
                return queryString;
            }
        });
    }

    function searchGrid() {
        $('#gridTable').ysTable('search');
        resetToolbarStatus();
    }

    function showAddEditDialog(add) {
        var id = '';
        var masterId = '';
        if (add) { masterId = $("#masterId").val();}
        else {
            var selectedRows = $("#gridTable").bootstrapTable("getSelections");
            if (!ys.checkRowEdit(selectedRows)) {
                return;
            }
            else {
                id = selectedRows[0].Id;
            }
        }
        ys.openDialog({
            title: id == '' ? "新建用户" : "修改用户",
            height:'580px',
            content: '@Url.Content("~/Sys/User/AddEditModal")' + '?id=' + id + '&masterId='+masterId,
            callback: function (index, layero) {
                var frame = window[layero.find('iframe')[0]['name']];
                frame.saveForm(index);
            }
        });
    }

    function showUpdateBelongedUserGroupsDialog(type) {
        var id = '';
        var selectedRows = $("#gridTable").bootstrapTable("getSelections");
        if (!ys.checkRowEdit(selectedRows)) {
            return;
        }

        id = selectedRows[0].Id;
         ys.openDialog({
            title: "角色选择",
             content: '@Url.Content("~/Sys/User/SelectBelongedUserGroupsModal")' + '?type=' + type+ '&id=' + id,
            width: "600px",
            height: "490px",
            shadeClose: true,
            callback: function (index, layero) {
                var childFrame = window[layero.find('iframe')[0]['name']];
                var ids = childFrame.getSelectedIds();
                ys.ajax({
                    url: '@Url.Content("~/Sys/User/UpdateBelongedUserGroups")' + '?type=' + type + '&id='+id+'&relatedIds=' + ids,
                    type: "post",
                    success: function (rst) {
                        if (rst.Flag == 1) {
                            ys.msgSuccess(rst.Message);
                        }
                        else {
                            ys.msgError(rst.Message);
                        }
                    }
                });
                layer.close(index);
            }
        });
    }

    function showUploadThumbnailDialog() {
        var id = '';
        var selectedRows = $("#gridTable").bootstrapTable("getSelections");
        if (!ys.checkRowEdit(selectedRows)) {
            return;
        }
        else {
            id = selectedRows[0].Id;
        }

        ys.openDialog({
            title: "上传Logo缩略图",
            height: '580px',
            btn: ['关闭'],
            content: '@Url.Content("~/Sys/User/UploadAttachmentModal")' + '?index=squareThumbnail&id=' + id,
            callback: function (index, layero) {
                var frame = window[layero.find('iframe')[0]['name']];
                frame.LeaveAndRefreshParent(index);
            }
        });
    }

    function deleteSelected() {
        var selectedRows = $("#gridTable").bootstrapTable("getSelections");
        if (ys.checkRowDelete(selectedRows)) {
            ys.confirm("确认要删除选中的" + selectedRows.length + "条数据吗？", function () {
                var ids = ys.getIds(selectedRows);
                ys.ajax({
                    url: '@Url.Content("~/Sys/User/DeleteSelected")' + '?ids=' + ids,
                    type: "post",
                    error: ys.ajaxError,
                    success: function (rst) {
                        if (rst.Flag == 1) {
                            ys.msgSuccess(rst.Message);
                            searchGrid();
                        }
                        else {
                            ys.msgError(rst.Message);
                        }
                    }
                });
            });
        }
    }

    function showManageOrganization() {
        var url = '@Url.Content("~/Sys/Organization/Manage")';
        createMenuItem(url, "组织管理");
    }

    function showResetPasswordDialog(id) {
        ys.openDialog({
            title: "重置密码",
            content: '@Url.Content("~/Sys/User/ResetPasswordModal")' + '?id=' + id,
            height: "220px",
            callback: function (index, layero) {
                var frame = window[layero.find('iframe')[0]['name']];
                frame.saveForm(index);
            }
        });
    }

</script>
